﻿using Microsoft.AspNetCore.Mvc;
using OaEntity.Models;
using PermissionAuthenticationDemo.Config;
using StackExchange.Redis;

namespace PermissionAuthenticationDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RedisController : CURDController
    {
        //注入redis服务，相当于java中的@AutoWire
        private readonly IConnectionMultiplexer connectionMultiplexer;

        public RedisController(IConnectionMultiplexer connectionMultiplexer, OaContext oaContext) : base(oaContext)
        {
            this.connectionMultiplexer = connectionMultiplexer ?? throw new ArgumentNullException(nameof(connectionMultiplexer));
        }

        [HttpGet("set/{key}/{value}")]
        public IActionResult Set(string key, string value)
        {
            //获取数据库实例，设置数据库是db1，不设置则默认的是db0
            var dbRedis = connectionMultiplexer.GetDatabase(1);
            //设置过期时间/秒
            TimeSpan expiration= TimeSpan.FromSeconds(60);
            dbRedis.StringSet(key, value, expiration);
            return Ok($"Key '{key}' set to '{value}'");
        }

        [HttpGet("get/{key}")]
        public IActionResult Get(string key)
        {
            var db = connectionMultiplexer.GetDatabase(1);
            var value = db.StringGet(key);
            if (value.HasValue)
            {
                return Ok(value);
            }
            else
            {
                return NotFound($"Key '{key}' not found");
            }
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetAuthCode(string phone)
        {
            var dbRedis = connectionMultiplexer.GetDatabase(1);
            TimeSpan expiration = TimeSpan.FromSeconds(60*5); //有效期是5分钟
            var authCode = CreateAuthCode.GenerateCaptcha(6);
            //将验证码保存到redis中
            //var authData = new HashEntry[]
            //{
            //    new HashEntry(phone, authCode),
            //};
            //dbRedis.HashSet("MobileAuthCode", authData);
            dbRedis.StringSet("AuthCode:moblieNumber:"+phone, authCode, expiration);
            return Ok(string.Format("验证码为：{0}，有效期为：{1}分钟", authCode, expiration.TotalMinutes));
        }

        /// <summary>
        /// 检索验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult NormalAuthCode(string phone)
        {
            var dbRedis = connectionMultiplexer.GetDatabase(1);
            bool isExistAuthCode = dbRedis.StringGet("AuthCode:moblieNumber:" + phone).HasValue;
            if (!!isExistAuthCode)
            {
                dbRedis.KeyDelete("AuthCode:moblieNumber:" + phone);
                return Ok(string.Format("验证码匹配成功"));
            }
            else
            {
                return Ok(string.Format("验证码错误，请重新输入"));
            }
        }
    }
}
